/*
 * AuxService.java
 *
 * Created on June 4, 2008, 11:17 PM
 *
 * Auxiliary Service is a daemon thread that can be run locally on the SPOT,
 * or remotely on another spot in order to collect more or specific sensor data
 * at a given interval from external sensors.
 */

package org.gunncs.daemons.telemetry;

import org.gunncs.actoriface.Sensor;
import org.gunncs.actoriface.*;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import com.sun.spot.util.Utils;

/**
 * This daemon pulls states from sensors periodically,
 * and relays them to other devices via radio -- providing 
 * telemetry data to hosts and other clients
 * Note that this is not exactly realtime, progressing 
 * as the radio data is sent. 
 * @author Anandg
 */
public class AuxService extends Thread{
    public static final int SLEEPTIME = 50;
    public static final int PORT = 38;
    boolean running;
    Sensor[] sensors;
    String message;
    DatagramConnection dgConnection;
    Datagram dg;
    
    /** Creates a new instance of AuxService */
    public AuxService(Sensor[] s) {
      sensors = s;
      message = "";
      try {
          // The Connection is a broadcast so we specify it in the creation string
          dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:"+PORT);
          // Then, we ask for a datagram with the maximum size allowed
          dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
      } catch (IOException ex) {
          System.out.println("Could not open radiogram broadcast connection");
          ex.printStackTrace();

      }
    }

    public void run(){
      running = true;
      while(running){
       //Send Message
       message = "";
       for (int i = 0; i < sensors.length; i++) {
           message += sensors[i].getID() + " ";
           for (int j = 0; j < sensors[i].getState().length-1; j++) {
               message += Robot.round(sensors[i].getState()[j]);
               message+=";";
           }
           message+="1.0";
           if(i<sensors.length-1)
               message += "\t";
       }
       try {
           // We send the message (UTF encoded)
           dg.reset();
           dg.writeUTF(message);
           dgConnection.send(dg);
       } catch (IOException ex) {
           ex.printStackTrace();
       }
       try{
          this.sleep(SLEEPTIME);
        }catch(InterruptedException e){
          e.printStackTrace();
        }
       }
       
    }
    
    public void notifyEvent(){
      
    }
    
}
